package com.cy.deepseeksport.service.search;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import java.util.LinkedHashSet;
import java.util.Set;

public class SearchResultProcessor {
    private static final ObjectMapper mapper = new ObjectMapper();
    private static final int MAX_LENGTH = 200;

    public static String process(BochaApiResponse response) {
        Set<String> uniqueContents = new LinkedHashSet<>(); // 保持顺序且去重
        StringBuilder output = new StringBuilder("=== 网络检索结果 ===\n\n");

        response.getMessages().forEach(message -> {
            try {
                if ("webpage".equals(message.getContentType())) {
                    processWebpage(message, uniqueContents);
                } else if ("baike_pro".equals(message.getContentType())) {
                    processWebpage(message, uniqueContents);
                }

                else {
                    processCard(message, uniqueContents);
                }
            } catch (Exception e) {
                // 忽略解析错误
            }
        });

        uniqueContents.forEach(content -> output.append(content).append("\n\n"));
        return output.toString();
    }

    private static void processWebpage(BochaApiResponse.Message message, Set<String> contents)
            throws Exception {

        WebpageContent content = mapper.readValue(message.getContent(), WebpageContent.class);
        content.getValue().forEach(webpage -> {
            String text = StringUtils.firstNonBlank(
                    webpage.getSummary(),
                    webpage.getSnippet(),
                    "无可用摘要"
            );
            String entry = String.format("[网页] %s\n来源：%s",
                    truncate(text),
                    shortenUrl(webpage.getUrl())
            );
            contents.add(entry);
        });
    }

    private static void processCard(BochaApiResponse.Message message, Set<String> contents)
            throws Exception {

        String rawContent = message.getContent();
        String text = StringUtils.substringBetween(rawContent, "\"summary\":", ",");
        if (text == null) text = StringUtils.substringBetween(rawContent, "\"content\":", ",");
        if (text == null) text = rawContent;

        contents.add(String.format("[卡片] %s",
                truncate(text.replaceAll("\"", "").trim())
        ));

    }

    private static String truncate(String text) {
        return text.length() > MAX_LENGTH ?
                text.substring(0, MAX_LENGTH) + "..." : text;
    }

    private static String shortenUrl(String url) {
        if (url == null) return "未知来源";
        if (url.length() > 40) {
            return url.substring(0, 20) + "..." + url.substring(url.length()-15);
        }
        return url;
    }
}